package com.xujie.sportsmeeting.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xujie.sportsmeeting.common.result.Result;
import com.xujie.sportsmeeting.dto.NoticePublishDTO;
import com.xujie.sportsmeeting.entity.NoticeReadRecord;
import com.xujie.sportsmeeting.entity.SysUser;
import com.xujie.sportsmeeting.entity.SystemNotice;
import com.xujie.sportsmeeting.service.NoticeReadRecordService;
import com.xujie.sportsmeeting.service.SysUserService;
import com.xujie.sportsmeeting.service.SystemNoticeService;
import com.xujie.sportsmeeting.vo.SystemNoticeVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统公告管理控制器
 */
@Tag(name = "系统公告管理", description = "公告发布、查询、阅读管理接口")
@RestController
@RequestMapping("/notices")
@RequiredArgsConstructor
public class SystemNoticeController {

    private final SystemNoticeService systemNoticeService;
    private final NoticeReadRecordService noticeReadRecordService;
    private final SysUserService sysUserService;

    @Operation(summary = "用户分页查询公告")
    @GetMapping
    public Result<Page<SystemNoticeVO>> pageUserNotices(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer noticeType,
            @RequestParam(required = false) String keyword) {
        
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        
        Page<SystemNotice> page = systemNoticeService.getUserNotices(
            currentUser.getId(), current, size, noticeType, keyword);
        
        // 转换为VO
        Page<SystemNoticeVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        voPage.setRecords(page.getRecords().stream().map(notice -> {
            SystemNoticeVO vo = convertToVO(notice);
            
            // 设置用户阅读状态
            vo.setHasRead(noticeReadRecordService.hasRead(notice.getId(), currentUser.getId()));
            vo.setHasConfirmed(noticeReadRecordService.hasConfirmed(notice.getId(), currentUser.getId()));
            
            // 设置有效性
            vo.setIsValid(systemNoticeService.isNoticeValid(notice));
            
            return vo;
        }).toList());
        
        return Result.success(voPage);
    }

    @Operation(summary = "管理员分页查询公告")
    @GetMapping("/admin")
    // @PreAuthorize("hasAnyAuthority('system:user', 'notice')") // 临时禁用权限检查
    public Result<Page<SystemNoticeVO>> pageAdminNotices(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer noticeType,
            @RequestParam(required = false) Integer publishStatus,
            @RequestParam(required = false) String keyword) {
        
        Page<SystemNotice> page = systemNoticeService.getAdminNotices(
            current, size, noticeType, publishStatus, keyword);
        
        // 转换为VO
        Page<SystemNoticeVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        voPage.setRecords(page.getRecords().stream().map(notice -> {
            SystemNoticeVO vo = convertToVO(notice);
            
            // 设置统计信息
            vo.setIsValid(systemNoticeService.isNoticeValid(notice));
            
            return vo;
        }).toList());
        
        return Result.success(voPage);
    }

    @Operation(summary = "发布公告")
    @PostMapping
    // @PreAuthorize("hasAnyAuthority('system:user', 'notice')") // 临时禁用权限检查
    public Result<Void> publishNotice(@Valid @RequestBody NoticePublishDTO noticeDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        
        SystemNotice notice = new SystemNotice();
        BeanUtils.copyProperties(noticeDTO, notice);
        notice.setPublisherId(currentUser.getId());
        
        systemNoticeService.publishNotice(notice);
        return Result.success("公告发布成功");
    }

    @Operation(summary = "保存草稿")
    @PostMapping("/draft")
    // @PreAuthorize("hasAnyAuthority('system:user', 'notice')") // 临时禁用权限检查
    public Result<Void> saveDraft(@Valid @RequestBody NoticePublishDTO noticeDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        
        SystemNotice notice = new SystemNotice();
        BeanUtils.copyProperties(noticeDTO, notice);
        notice.setPublisherId(currentUser.getId());
        notice.setPublishStatus(0); // 草稿状态
        
        systemNoticeService.save(notice);
        return Result.success("草稿保存成功");
    }

    @Operation(summary = "更新公告")
    @PutMapping("/{id}")
    // @PreAuthorize("hasAnyAuthority('system:user', 'notice')") // 临时禁用权限检查
    public Result<Void> updateNotice(@PathVariable Long id, @Valid @RequestBody NoticePublishDTO noticeDTO) {
        SystemNotice existNotice = systemNoticeService.getById(id);
        if (existNotice == null) {
            return Result.error("公告不存在");
        }
        
        SystemNotice notice = new SystemNotice();
        BeanUtils.copyProperties(noticeDTO, notice);
        notice.setId(id);
        
        systemNoticeService.updateById(notice);
        return Result.success("公告更新成功");
    }

    @Operation(summary = "撤回公告")
    @PostMapping("/{id}/withdraw")
    // @PreAuthorize("hasAnyAuthority('system:user', 'notice')") // 临时禁用权限检查
    public Result<Void> withdrawNotice(@PathVariable Long id) {
        systemNoticeService.withdrawNotice(id);
        return Result.success("公告撤回成功");
    }

    @Operation(summary = "置顶/取消置顶公告")
    @PostMapping("/{id}/top")
    // @PreAuthorize("hasAnyAuthority('system:user', 'notice')") // 临时禁用权限检查
    public Result<Void> setTopNotice(@PathVariable Long id, @RequestParam Integer isTop) {
        systemNoticeService.setTopNotice(id, isTop);
        return Result.success(isTop == 1 ? "公告置顶成功" : "取消置顶成功");
    }

    @Operation(summary = "删除公告")
    @DeleteMapping("/{id}")
    // @PreAuthorize("hasAnyAuthority('system:user', 'notice')") // 临时禁用权限检查
    public Result<Void> deleteNotice(@PathVariable Long id) {
        systemNoticeService.removeById(id);
        return Result.success("公告删除成功");
    }

    @Operation(summary = "查看公告详情")
    @GetMapping("/{id}")
    public Result<SystemNoticeVO> getNoticeDetail(@PathVariable Long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        
        SystemNotice notice = systemNoticeService.getNoticeDetail(id, currentUser.getId());
        SystemNoticeVO vo = convertToVO(notice);
        
        // 设置用户阅读状态
        vo.setHasRead(noticeReadRecordService.hasRead(id, currentUser.getId()));
        vo.setHasConfirmed(noticeReadRecordService.hasConfirmed(id, currentUser.getId()));
        
        // 获取阅读记录
        List<NoticeReadRecord> readRecords = noticeReadRecordService.getUserReadRecords(currentUser.getId());
        NoticeReadRecord userRecord = readRecords.stream()
                .filter(record -> record.getNoticeId().equals(id))
                .findFirst().orElse(null);
        
        if (userRecord != null) {
            vo.setReadTime(userRecord.getReadTime());
        }
        
        vo.setIsValid(systemNoticeService.isNoticeValid(notice));
        
        return Result.success(vo);
    }

    @Operation(summary = "确认阅读公告")
    @PostMapping("/{id}/confirm")
    public Result<Void> confirmRead(@PathVariable Long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        
        noticeReadRecordService.confirmRead(id, currentUser.getId());
        return Result.success("确认阅读成功");
    }

    @Operation(summary = "批量确认阅读")
    @PostMapping("/batch-confirm")
    public Result<Void> batchConfirmRead(@RequestBody List<Long> noticeIds) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        
        noticeReadRecordService.batchConfirmRead(noticeIds, currentUser.getId());
        return Result.success("批量确认成功");
    }

    @Operation(summary = "获取置顶公告")
    @GetMapping("/top")
    public Result<List<SystemNoticeVO>> getTopNotices() {
        List<SystemNotice> notices = systemNoticeService.getTopNotices();
        List<SystemNoticeVO> voList = notices.stream().map(this::convertToVO).toList();
        
        return Result.success(voList);
    }

    @Operation(summary = "获取最新公告")
    @GetMapping("/latest")
    public Result<List<SystemNoticeVO>> getLatestNotices(@RequestParam(defaultValue = "5") Integer limit) {
        List<SystemNotice> notices = systemNoticeService.getLatestNotices(limit);
        List<SystemNoticeVO> voList = notices.stream().map(this::convertToVO).toList();
        
        return Result.success(voList);
    }

    @Operation(summary = "获取未读公告数量")
    @GetMapping("/unread-count")
    public Result<Long> getUnreadCount() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        
        Long count = systemNoticeService.countUnreadNotices(currentUser.getId());
        return Result.success(count);
    }

    @Operation(summary = "获取公告统计信息")
    @GetMapping("/{id}/statistics")
    // @PreAuthorize("hasAnyAuthority('system:user', 'notice')") // 临时禁用权限检查
    public Result<Map<String, Object>> getNoticeStatistics(@PathVariable Long id) {
        SystemNotice notice = systemNoticeService.getById(id);
        if (notice == null) {
            return Result.error("公告不存在");
        }
        
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("readCount", notice.getReadCount());
        statistics.put("confirmCount", noticeReadRecordService.getNoticeReadCount(id));
        statistics.put("unconfirmedUsers", List.of());
        
        return Result.success(statistics);
    }

    @Operation(summary = "获取公告类型选项")
    @GetMapping("/types")
    public Result<List<Map<String, Object>>> getNoticeTypes() {
        List<Map<String, Object>> types = List.of(
            Map.of("value", 1, "label", "系统公告", "icon", "📢"),
            Map.of("value", 2, "label", "比赛通知", "icon", "🏃"),
            Map.of("value", 3, "label", "成绩公布", "icon", "🏆"),
            Map.of("value", 4, "label", "紧急通知", "icon", "⚠️")
        );
        
        return Result.success(types);
    }

    /**
     * 转换为VO对象
     */
    private SystemNoticeVO convertToVO(SystemNotice notice) {
        SystemNoticeVO vo = new SystemNoticeVO();
        BeanUtils.copyProperties(notice, vo);
        
        // 查询发布人信息
        if (notice.getPublisherId() != null) {
            SysUser publisher = sysUserService.getById(notice.getPublisherId());
            if (publisher != null) {
                vo.setPublisherName(publisher.getRealName());
            }
        }
        
        return vo;
    }
}
